package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.DomainIsDeleteStatusEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.HospitalSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2022/12/19 - 14:19
 * @Author: Hyoung
 * @Description:
 */
@Service
public class HospitalServiceImpl implements HospitalService {


    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private HospitalSetService hospitalSetService;


    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public void save(Map<String, Object> paramMap) {
        String json = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(json, Hospital.class);
        String hoscode = hospital.getHoscode();

        HospitalSet hospitalSet = hospitalSetService.selectByHoscode(hoscode);

        if (hospitalSet == null) {
            throw new YyghException(ResultCodeEnum.HOSPITAL_OPEN);
        }
        if (hospitalSet.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.HOSPITAL_LOCK);
        }

        // 根据hoscode查询医院是否已经存在mongodb数据库中
        Hospital havaHospital = hospitalRepository.findByHoscode(hoscode);
        // 如果不存在则新增

        if (havaHospital == null) {
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(DomainIsDeleteStatusEnum.UNDELETED.getIsDelete());  // 设置状态未删除
            hospitalRepository.save(hospital);

        } else {  // 如果存在则修改

            hospital.setId(havaHospital.getId());
            hospital.setCreateTime(havaHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(DomainIsDeleteStatusEnum.UNDELETED.getIsDelete());  // 设置状态未删除
            hospital.setStatus(0);
            hospitalRepository.save(hospital); // 有id为修改
        }

    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.findByHoscode(hoscode);
    }

    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, String hosname) {
        Sort sort = Sort.by(Sort.Direction.ASC, "hoscode");
        PageRequest pageable = PageRequest.of(page - 1, limit, sort);

        ExampleMatcher matching = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);

        Hospital hospital = new Hospital();
        hospital.setHosname(hosname);
        Example<Hospital> of = Example.of(hospital, matching);
        // 获取结果
        Page<Hospital> pageModel = hospitalRepository.findAll(of, pageable);
        // 查找数据字典的名字
        pageModel.getContent().forEach(this::packHospital);
        return pageModel;
    }

    @Override
    public void updateStatus(String id, Integer status) {

        Optional<Hospital> optional = hospitalRepository.findById(id);
        if (optional.isPresent()) {
            Hospital hospital = optional.get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }


    @Override
    public Hospital getDetail(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        this.packHospital(hospital);
        return hospital;
    }

    @Override
    public List<Hospital> selectList(String keywords, String levelId, String areaId) {
        ExampleMatcher matching = ExampleMatcher.matching()
                .withMatcher("hosname", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("hostype", ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("districtCode", ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("isDeleted", ExampleMatcher.GenericPropertyMatchers.exact());
        Hospital hospital = new Hospital();
        hospital.setHosname(keywords);
        hospital.setHostype(levelId);
        hospital.setDistrictCode(areaId);
        hospital.setStatus(1);
        hospital.setIsDeleted(0);

        Example<Hospital> hospitalExample = Example.of(hospital, matching);
        List<Hospital> list = hospitalRepository.findAll(hospitalExample);
        list.stream().forEach(this::packHospitalHostype);
        return list;
    }

    @Override
    public Hospital show(String id) {
        Optional<Hospital> optional = hospitalRepository.findById(id);
        if (optional.isPresent()) {
            Hospital hospital = optional.get();
            return hospital;

        }
        return null;
    }

    /**
     * 查找数据中数据字典的value的对应的值，并封装到hospital对象的扩展属性param中
     *
     * @param hospital
     */
    private void packHospital(Hospital hospital) {

        // 远程调用,查找数据字典中的名字
        String dictName = dictFeignClient.getName("Hostype", hospital.getHostype());
        hospital.getParam().put("hostypeString", dictName);

        String provinceName = dictFeignClient.getName(null, hospital.getProvinceCode());
        String cityName = dictFeignClient.getName(null, hospital.getCityCode());
        String districtName = dictFeignClient.getName(null, hospital.getDistrictCode());

        hospital.getParam().put("fullAddress", provinceName + cityName + districtName + hospital.getAddress());
    }

    /**
     * 查找数据中数据字典的value的对应的值，并封装到hospital对象的扩展属性param中
     *
     * @param hospital
     */
    private void packHospitalHostype(Hospital hospital) {

        // 远程调用,查找数据字典中的名字
        String dictName = dictFeignClient.getName("Hostype", hospital.getHostype());
        hospital.getParam().put("hostypeString", dictName);

    }
}
